package org.apache.ibatis.test202308;

import org.apache.ibatis.executor.statement.RoutingStatementHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.*;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.util.Properties;

/**
 * @Author: ShipTang
 * @Description:
 * @Date: 2023/8/2 19:45
 */
@Intercepts({@Signature(
        type = StatementHandler.class,
        method = "prepare",
        args = {Connection.class, Integer.class})})
public class StatementInterceptor implements Interceptor {

    private Properties properties;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        RoutingStatementHandler routingStatementHandler = (RoutingStatementHandler) invocation.getTarget();
        BoundSql boundSql = routingStatementHandler.getBoundSql();
        System.out.println("修改前:" + boundSql.getSql());

        //反射修改
        Field field = BoundSql.class.getDeclaredField("sql");
        field.setAccessible(true);
        String oldSql = (String) field.get(boundSql);
        field.set(boundSql, oldSql.replace("user", "user_copy1"));
        System.out.println("修改后:" + boundSql.getSql());

        Object returnObject = invocation.proceed();
        return returnObject;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        this.properties = properties;
    }
}
